package com.nbot.server.workers.impl;


import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.log.StaticLog;
import com.nbot.common.command.BaseCommand;
import com.nbot.common.command.s2b.ReportCommand;
import com.nbot.server.BotServer;
import com.nbot.server.algorithm.MaxDiffValueImpl;
import com.nbot.server.algorithm.MovingAverageImpl;
import com.nbot.server.algorithm.SetNumValue;
import com.nbot.server.algorithm.TrendJudgeImpl;
import com.nbot.server.domain.*;
import com.nbot.server.mapper.third.SRPResultMapper;
import com.nbot.server.properties.NbotProperties;
import com.nbot.server.service.*;
import com.nbot.server.util.NbotStringUtil;
import com.nbot.server.workers.OpcWorker;
import org.jinterop.dcom.common.JIException;
import org.openscada.opc.lib.common.AlreadyConnectedException;
import org.openscada.opc.lib.common.ConnectionInformation;
import org.openscada.opc.lib.common.NotConnectedException;
import org.openscada.opc.lib.da.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * opc数据读取类
 */
public class OpcWorker3ChangImpl implements OpcWorker {
    private static final Log log = LogFactory.get();

    @Autowired
    private NbotProperties nbotProperties;
    @Autowired
    //private PointService pointService;
    private AlarmpointService alarmpointService;

    @Autowired //add wyzc 180606
    private AnalogalarmService analogalarmService;

    @Autowired //add wyzc 180616
    private RelevancealarmService relevancealarmService;

    @Autowired
    private BotServer botServer;
    @Autowired
    private ChecklogService checklogService;

    @Autowired
    private AlarmService alarmService;

    @Autowired
    private WaterwellService waterwellService;

    @Autowired
    private OilwellService oilwellService;

    @Autowired
    private PlanInjectWaterService planInjectWaterService;

    @Autowired
    private TransmissstationService transmissstationService;

    @Autowired
    private TransmissstationopckeyService transmissstationopckeyService;

    @Autowired
    private EverytwohoursproductionService everytwohoursproductionService;

    private static ScheduledExecutorService pool = Executors.newScheduledThreadPool(50);

    private static int DB_COUNT = 0;

    private SetNumValue snv = new SetNumValue();//格式化小数
    /**
     * 获取server对象
     */

    private Server getOpcServer() {
        ConnectionInformation ci = new ConnectionInformation();
        ci.setHost(nbotProperties.getOpc().getIp());
        /*server端名称，需要更改*/
        ci.setClsid(nbotProperties.getOpc().getClsid());
        ci.setUser(nbotProperties.getOpc().getUser());
        ci.setPassword(nbotProperties.getOpc().getPassword());

        return new Server(ci, pool);
    }


    @Override
    public String readData(String opcKey) {

        Server server = this.getOpcServer();

        try {
            server.connect();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

        Group group = null;
        try {
            group = server.addGroup("Group1" );
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        Item item = null; //get item for writing
        try {
            item = group.addItem(opcKey);
        } catch (Exception e) {
            //e.printStackTrace();
            return "";
        }

        ItemState itemState = null;
        try {
            itemState = item.read(true);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        log.debug("<<< first read: " + itemState.getValue().toString());

        server.disconnect();
        String tmp = StrUtil.removePrefix(itemState.getValue().toString(), "[[" );
        tmp = StrUtil.removeSuffix(tmp, "]]" );
        return tmp;

    }

    @Override
    public String checkAllPoint() {//3厂油井状态+瞬时流量
        log.debug("checkOilWellStatus()" );
        List<AlarmpointDO> points = null;
        points = alarmpointService.listAll();
        if (points == null) {
            return null;
        }

        Server server = this.getOpcServer();
        try {
            server.connect();
        } catch (UnknownHostException | JIException | AlreadyConnectedException e) {
            e.printStackTrace();
        }

        Group group = null;
        try {
            group = server.addGroup("Group1" );
        } catch (NotConnectedException | UnknownHostException | DuplicateGroupException | JIException e) {
            e.printStackTrace();
        }

        List<Item> itemList = new ArrayList<Item>();

        try {
            for (AlarmpointDO p : points) {
                try {
                    itemList.add(group.addItem(p.getGetdatapath()));
                }catch (AddFailedException e){
//                    System.err.println("开关量："+p.getAutoid()+"添加失败！");
                    continue;
                }
            }
        } catch (JIException e) {
            e.printStackTrace();
        }

        if (itemList.isEmpty()) {
            return null;
        }

        ItemState itemState = null;
        try {
            for (Item it : itemList) {
                itemState = it.read(true);
                String tmp = StrUtil.removePrefix(itemState.getValue().toString(), "[[" );
                tmp = StrUtil.removeSuffix(tmp, "]]" ).split("\\.")[0];

                AlarmpointDO actPoint = null;
                for (AlarmpointDO p : points) {
                    if (p.getGetdatapath().equals(it.getId())) {
                        actPoint = p;
                    }
                }
                if (actPoint != null) {
                    BaseCommand reportCommand = null;

                    TrendJudgeImpl tj = new TrendJudgeImpl();//趋势
                    float[] tjdata = {Float.parseFloat(actPoint.getVf()),Float.parseFloat(actPoint.getVs()),Float.parseFloat(actPoint.getVt()),Float.parseFloat(tmp)};
                    String trend = tj.trendResult(tjdata);
                    if (Float.parseFloat(tmp)>1){
                        tmp = String.valueOf(Math.floor(Float.parseFloat(tmp)));
                    }
                    MovingAverageImpl lvb = new MovingAverageImpl();//滤波算法 add wyzc 180606
                    AlarmpointDO updateValue = lvb.getBoolMAvg(actPoint,tmp);
                    alarmpointService.update(updateValue);
                    tmp = updateValue.getTmp();

                    String checkval = null;
                    String alarmType = null;
                    if (actPoint.getDatatype().equals("oilwellfunc") && tmp.equals(actPoint.getBoolt()) && trend.equals("decrease")) {
                        reportCommand = new ReportCommand();
                        ((ReportCommand) reportCommand).setReportMsg("[" + actPoint.getDispdesc() + "]停止" );
                        ((ReportCommand) reportCommand).setWarnLevel("报警级别为" + actPoint.getAlarmLevelStr());
                        ((ReportCommand) reportCommand).setValueNow("现场实时状态：" + tmp);
                        checkval = "停运";
                        alarmType = "油井";
                    }else if (actPoint.getDatatype().equals("flow") && Float.parseFloat(tmp) <= Float.parseFloat(actPoint.getBoolt()) && !trend.equals("same")){
                        reportCommand = new ReportCommand();
                        ((ReportCommand) reportCommand).setReportMsg("[" + actPoint.getDispdesc() + "]为 0" );
                        ((ReportCommand) reportCommand).setWarnLevel("报警级别为" + actPoint.getAlarmLevelStr());
                        ((ReportCommand) reportCommand).setValueNow("现场实时状态：" + tmp);
                        checkval = "停运";
                        alarmType = "水井";
                    }
                    if (reportCommand != null) {
                        //查询报警记录里当前opc点，在10min内是否有相同值的报警，有则不发送报警，无则发送报警
                        Calendar beforeTime = Calendar.getInstance();
                        beforeTime.add(Calendar.MINUTE, - 30);//计算n分钟前的date对象
                        Date beforeD = beforeTime.getTime();
                        List<ChecklogDO> logs = null;
                        logs = checklogService.logInNmins(actPoint.getSearchdesc(), tmp, beforeD.getTime() / 1000);

                        //将当前报警值进行保存
                        //如果10分钟内没有相同，则发送报警指令

                        if (logs.isEmpty()) {
                            ((ReportCommand) reportCommand).setPriority(3);
                            try {
                                BotServer.addUartMsg(reportCommand);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            log.debug("BotServer.comandQueue.size()：" + BotServer.uartQueue.size());
                            log.debug("发送报警指令：" + reportCommand.toString());

                            ChecklogDO checklog = new ChecklogDO();
                            checklog.setTag(actPoint.getSearchdesc());
                            checklog.setDispdesc(((ReportCommand) reportCommand).getReportMsg());
                            checklog.setChecktimestamp(new Date());
                            checklog.setCheckvalue(checkval);
                            checklog.setTruthvalue(tmp);
                            checklog.setAlarmlevel(alarmType);
                            checklogService.insert(checklog);
                        }
                    }
                }
            }
        } catch (JIException e) {
            e.printStackTrace();
        }
        log.debug("<<< first read: " + itemState.getValue().toString());

        server.disconnect();
        return null;
    }

    @Override
    public String checkOilWell() {//油井一级故障
        log.debug("checkOilWell()" );

        List<OilwellDO> wells = null;
        wells = oilwellService.listAll();
        if (wells == null) {
            return null;
        }

        for (OilwellDO o : wells) {
            String dateStr = NbotStringUtil.getTodayStr();
            List<SRPResultWithBLOBs> tarwells = null;
            try {
                tarwells = oilwellService.getTagWellList(SRPResultMapper.TABLE_PRE_STR + dateStr, o.getOilwellname());
            } catch (Exception e) {
                StaticLog.error(e.getMessage());
            }
            SRPResultWithBLOBs tarwell = null;
            if (!(tarwells == null || tarwells.isEmpty())) {
                tarwell = tarwells.get(0);
            }
            if (tarwell == null || tarwell.getAcquireDatetime() == null || tarwell.getFaultName() == null) {
                continue;
            } else {
                List<SRPFaultWithBLOBs> faultList = oilwellService.getFaultList();
                for (SRPFaultWithBLOBs f : faultList){
                    String checkval = null;
                    BaseCommand reportCommand = null;
                    if (tarwell.getFaultName().contains(f.getFaultName())){
                        reportCommand = new ReportCommand();
                        ((ReportCommand) reportCommand).setReportMsg("[" + o.getOilwellname().replaceAll("_","") + f.getFaultName() +"]报警");
                        ((ReportCommand) reportCommand).setWarnLevel("报警级别为" + NbotStringUtil.getAlarmLevelStr("3"));
                        ((ReportCommand) reportCommand).setValueNow("现场故障为" + f.getFaultName());
                        checkval="一级故障";
                    }
                    if (reportCommand != null) {
                        Calendar beforeTime = Calendar.getInstance();
                        beforeTime.add(Calendar.MINUTE, -Integer.parseInt("30"));//计算n分钟前的date对象
                        Date beforeD = beforeTime.getTime();
                        List<ChecklogDO> logs = null;
                        String tag = o.getOilwellname();
                        logs = checklogService.logInNmins(tag, checkval, beforeD.getTime() / 1000);

                        //将当前报警值进行保存
                        //如果10分钟内没有相同，则发送报警指令
                        if (logs.isEmpty()) {
                            int priority = 2;
                            ((ReportCommand) reportCommand).setPriority(priority);
//                            botServer.addCommand(reportCommand);
                            try {
                                BotServer.addUartMsg(reportCommand);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            log.debug("BotServer.comandQueue.size()：" + BotServer.uartQueue.size());
                            log.debug("发送油井报警指令：" + reportCommand.toString());

                            ChecklogDO checklog = new ChecklogDO();
                            checklog.setTag(tag);
                            checklog.setDispdesc(((ReportCommand) reportCommand).getReportMsg());
                            checklog.setChecktimestamp(new Date());
                            checklog.setCheckvalue(checkval);
                            checklog.setTruthvalue(tarwell.getFaultName());
                            checklog.setAlarmlevel("油井");
                            checklogService.insert(checklog);
                        }
                    }
                }
            }
        }
        return null;
    }

    @Override
    public String checkWaterWell() {//水井
        log.debug("checkWaterWell()" );

        List<WaterwellDO> wells = null;
        wells = waterwellService.listAll();
        if (wells == null) {
            return null;
        }

        for (WaterwellDO w : wells) {
            String wellname = w.getWellname();
            WellWaterInfor wellWaterInfor= null;
            List<WellRtGkInfor> tarwells= null;
            try{
                wellWaterInfor  = waterwellService.getWellId(wellname);
                tarwells = waterwellService.getTagWell(wellWaterInfor.getWellid());
            }catch (Exception e){
                StaticLog.error(e.getMessage());
            }

            PlanInjectWaterDO realPJInfo = planInjectWaterService.get(wellname);
            WellRtGkInfor tarwell = null;
            if (!(tarwells == null || tarwells.isEmpty())) {
                tarwell = tarwells.get(0);
            }
            if (tarwell == null || tarwell.getTjtime() == null || tarwell.getSzl() == null|| realPJInfo.getInjection()== null) {
                continue;
            } else {
                BaseCommand reportCommand = null;
                String checkval = null;
                BigDecimal interval = new BigDecimal(tarwell.getTjtime().getHours() - 7);//時間；
                if (interval.compareTo(BigDecimal.valueOf(0))<1){
                    interval = interval.add(new BigDecimal(24));
                }
                BigDecimal avgyzl = new BigDecimal(realPJInfo.getInjection()).divide(new BigDecimal(24.0),3,RoundingMode.CEILING);//配注量/24H
                BigDecimal yzl = avgyzl.multiply(interval);//應注量
                    if (tarwell.getSzl().compareTo(yzl.add(new BigDecimal(0.5)))>0) {
                    reportCommand = new ReportCommand();
                    checkval = "超注";
                    ((ReportCommand) reportCommand).setReportMsg("[" + w.getWellname().replaceAll("_","") + "]超注报警");
                    ((ReportCommand) reportCommand).setWarnLevel("报警级别为" + NbotStringUtil.getAlarmLevelStr("1"));
                    ((ReportCommand) reportCommand).setValueNow("当前实注量：" + tarwell.getSzl());
                } else if (tarwell.getSzl().compareTo(yzl.subtract(new BigDecimal(0.5)))<0) {
                    reportCommand = new ReportCommand();
                    checkval = "欠注";
                    ((ReportCommand) reportCommand).setReportMsg("[" + w.getWellname().replaceAll("_","") + "]欠注报警");
                    ((ReportCommand) reportCommand).setWarnLevel("报警级别为" + NbotStringUtil.getAlarmLevelStr("1"));
                    ((ReportCommand) reportCommand).setValueNow("当前实注量：" + tarwell.getSzl());
                }
                if (reportCommand != null) {
                    Calendar beforeTime = Calendar.getInstance();
                    beforeTime.add(Calendar.MINUTE, -90);//计算n分钟前的date对象
                    Date beforeD = beforeTime.getTime();
                    List<ChecklogDO> logs = null;
                    String tag = tarwell.getWellid();
                    logs = checklogService.logInNmins(tag, checkval, beforeD.getTime() / 1000);

                    //将当前报警值进行保存
                    //如果10分钟内没有相同，则发送报警指令
                    if (logs.isEmpty()) {
                        int priority = 2;
                        ((ReportCommand) reportCommand).setPriority(priority);
                        try {
                            BotServer.addUartMsg(reportCommand);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
//                        botServer.addCommand(reportCommand);
                        log.debug("BotServer.comandQueue.size()：" + BotServer.uartQueue.size());
                        log.debug("发送水井报警指令：" + reportCommand.toString());

                        ChecklogDO checklog = new ChecklogDO();
                        checklog.setTag(tarwell.getWellid());
                        checklog.setDispdesc(((ReportCommand) reportCommand).getReportMsg());
                        checklog.setChecktimestamp(new Date());
                        checklog.setCheckvalue(checkval);
                        checklog.setTruthvalue(String.valueOf(tarwell.getSzl()));
                        checklog.setAlarmlevel("水井");
                        checklogService.insert(checklog);
                    }
                }
            }
        }
        return null;
    }
    private static void setCount(int count) {
        synchronized (OpcWorker3ChangImpl.class) {
            DB_COUNT = count;
        }
    }
    @Override
    public synchronized void checkAllAnalogPoint() {
        log.debug("checkAnalogPoint()" );
//        StaticLog.info("执行3厂mysql报警监控任务");

        //第一次运行时
        if (DB_COUNT == 0) {
            int tmpInt;
            try {
                tmpInt = alarmService.count(null);
                setCount(tmpInt - 1);
            } catch (Exception e) {
                return;
            }
        }
        //获取当前总数
        int currentCount;

        try {
            currentCount = alarmService.count(null);
        } catch (Exception e) {
            return;
        }
        // 大于时表示有新报警
        if (currentCount > DB_COUNT) {
            int discar = currentCount - DB_COUNT;
            Map<String, Object> params = new HashMap<>();
//            params.put("sort", "EventTime");
//            params.put("order", "desc");
            params.put("offset", DB_COUNT);
            params.put("limit", discar);
            List<AlarmDO> list = alarmService.list(params);
            setCount(currentCount);
            BaseCommand reportCommand = null;
            for (AlarmDO alarmDO : list) {
                AnalogalarmDO analogpoints = null;
                String tag = alarmDO.getTagname();
                analogpoints = analogalarmService.getopcdatapath(tag);
                if (analogpoints != null && alarmDO.getEventtype().equals("报警")) {
                    reportCommand = new ReportCommand();
                    ((ReportCommand) reportCommand).setReportMsg("[" + alarmDO.getTagcomment().replaceAll("_","") + "]超"+alarmDO.getAlarmtype()+"限报警" );
                    ((ReportCommand) reportCommand).setWarnLevel("报警级别为" + NbotStringUtil.getAlarmLevelStr("2"));
                    ((ReportCommand) reportCommand).setValueNow("现场实时值为" + snv.setfloat(Float.parseFloat(alarmDO.getAlarmvalue()),2));
                }
                if (reportCommand != null) {//move out by wyzc 180607
                    //查询报警记录里当前opc点，在10min内是否有相同值的报警，有则不发送报警，无则发送报警
                    Calendar beforeTime = Calendar.getInstance();
                    beforeTime.add(Calendar.MINUTE, -Integer.parseInt(nbotProperties.getOpc().getInterval()));//计算n分钟前的date对象
                    Date beforeD = beforeTime.getTime();
                    List<ChecklogDO> logs = null;
                    List<ChecklogDO> logsD = null;
                    String disp =((ReportCommand) reportCommand).getReportMsg();
                    logsD = checklogService.logInNminsBydisp(disp, alarmDO.getAlarmtype(), beforeD.getTime() / 1000);
                    logs = checklogService.logInNmins(tag, alarmDO.getAlarmtype(), beforeD.getTime() / 1000);

                    //将当前报警值进行保存
                    //如果10分钟内没有相同，则发送报警指令
                    if ( logs.isEmpty() && logsD.isEmpty() && disp.contains(alarmDO.getAlarmtype())) {
                        ChecklogDO checklog = new ChecklogDO();

                        int priority = 2;
                        ((ReportCommand) reportCommand).setPriority(priority);
//                        botServer.addCommand(reportCommand);
                        try {
                            BotServer.addUartMsg(reportCommand);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                        log.debug("BotServer.comandQueue.size()：" + BotServer.uartQueue.size());
                        log.debug("发送生产报警指令：" + reportCommand.toString());

                        checklog.setTag(tag);
                        checklog.setDispdesc(disp);
                        checklog.setChecktimestamp(new Date());
                        checklog.setCheckvalue(alarmDO.getAlarmtype());
                        checklog.setTruthvalue(alarmDO.getAlarmvalue());
                        checklog.setAlarmlevel("生产");
                        checklogService.insert(checklog);
                    }
                }
            }
        }else{
            log.info("当前行数："+currentCount+"；当前计数："+DB_COUNT);
            setCount(currentCount);
        }
    }

    @Override
    public void checkRelevanceAlarm() throws JIException {//产量

        Date now = new Date();
        int hours = now.getHours();
        int minute = now.getMinutes();
        if ( hours % 2 == 1 && minute < 3) {
            StaticLog.info("执行3厂产量报警任务");

            List<TransmissstationDO> transStations = null;
            transStations = transmissstationService.list(null);
            if (transStations == null) {
                return;
            }
            TransmissionDatasaveBySitenKey tsKey = new TransmissionDatasaveBySitenKey();
            EverytwohoursproductionDO ethp = new EverytwohoursproductionDO();//calculate production

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-M-d");//日期格式
            String date = dateFormat.format(now);
            ethp.setDate(date);//calculate production

            Calendar cal = Calendar.getInstance();
            cal.setTime(now);
            cal.add(Calendar.HOUR_OF_DAY, -7);
            date = dateFormat.format(cal.getTime());

            for (TransmissstationDO ts : transStations) {
                tsKey.setSiteName(ts.getStationname());
                tsKey.setDay(date);
                TransmissionDatasaveBySiten tsInfo = transmissstationService.getPlanProduction(tsKey);
                if (tsInfo == null || tsInfo.getProductionPlanAllday().equals("") || tsInfo.getProductionPlanAllday() == null) {
                    cal.add(Calendar.HOUR_OF_DAY, -24);
                    date = dateFormat.format(cal.getTime());
                    tsKey.setDay(date);
                    tsInfo = transmissstationService.getPlanProduction(tsKey);
                    if (tsInfo == null || tsInfo.getProductionPlanAllday().equals("") || tsInfo.getProductionPlanAllday() == null) {
                        StaticLog.info("查询配产失败！");
                        return;
                    }
                }

                ethp.setStation(ts.getStationname());
                List<EverytwohoursproductionDO> twoHoursList = everytwohoursproductionService.listByDAS(ethp.getDate(),ts.getStationname());
                if (twoHoursList.isEmpty()){
                    everytwohoursproductionService.save(ethp);
                }
                float planproduction = Float.parseFloat(tsInfo.getProductionPlanAllday());//配产量

                List<TransmissstationopckeyDO> productionInfoList = transmissstationopckeyService.getBystationName(ts.getStationname());

                log.info("读List条件："+ts.getStationname()+"，读取："+productionInfoList.size());

                Server server = this.getOpcServer();
                try {
                    server.connect();
                } catch (UnknownHostException | AlreadyConnectedException e) {
                    e.printStackTrace();
                } catch (JIException e) {
                    e.printStackTrace();
                }

                Group group = null;
                try {
                    group = server.addGroup("Group1");
                } catch (NotConnectedException | DuplicateGroupException e) {
                    e.printStackTrace();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (JIException e) {
                    e.printStackTrace();
                }

                float realProduction = 0.00f;
                TransmissstationopckeyDO updata = new TransmissstationopckeyDO();
                String updateKey = null;

                for (TransmissstationopckeyDO pi : productionInfoList) { //add by wyzc 180607
                    String path = pi.getGetdatapath();
                    log.info("OPC:"+pi.getDesp());
                    try {
                        ItemState itemState = group.addItem(path).read(true);
                        String tmp = StrUtil.removePrefix(itemState.getValue().toString(), "[[");
                        tmp = StrUtil.removeSuffix(tmp, "]]");

                        if (tmp.matches("([0-9]\\d*\\.?\\d*)|((-)?[0-9]\\d*\\.?\\d*)|(-?\\d+.?\\d*)[Ee]{1}(-?\\d+)")) {
                            if (pi.getAddflag().equals("1")) {
                                realProduction += (Float.parseFloat(tmp)-Float.parseFloat(pi.getBackup()));
                                updata.setBackup(tmp);
                                if (Integer.parseInt(pi.getAutoid()) % 2 == 1){
                                    updateKey = pi.getAutoid();
                                }
                            } else {
                                realProduction -= (Float.parseFloat(tmp)-Float.parseFloat(pi.getBackup()));
                                updata.setBackup(tmp);
                            }
                        } else {//非数值
                            continue;
                        }
                        updata.setAutoid(pi.getAutoid());
                        transmissstationopckeyService.update(updata);
                    } catch (AddFailedException e) {
                        continue;
                        //e.printStackTrace();
                    }
                }

                realProduction = snv.setfloat(realProduction,2);
                if (realProduction == 0.00f) {
                    log.info("无产量！");
                }else {
                    switch (hours) {
                        case 1:
                            ethp.setOne(String.valueOf(realProduction));
                            break;
                        case 3:
                            ethp.setThree(String.valueOf(realProduction));
                            break;
                        case 5:
                            ethp.setFive(String.valueOf(realProduction));
                            break;
                        case 7:
                            ethp.setSeven(String.valueOf(realProduction));
                            break;
                        case 9:
                            ethp.setNine(String.valueOf(realProduction));
                            break;
                        case 11:
                            ethp.setEleven(String.valueOf(realProduction));
                            break;
                        case 13:
                            ethp.setThirteen(String.valueOf(realProduction));
                            break;
                        case 15:
                            ethp.setFifteen(String.valueOf(realProduction));
                            break;
                        case 17:
                            ethp.setSeventeen(String.valueOf(realProduction));
                            break;
                        case 19:
                            ethp.setNineteen(String.valueOf(realProduction));
                            break;
                        case 21:
                            ethp.setTwentyone(String.valueOf(realProduction));
                            break;
                        case 23:
                            ethp.setTwentythree(String.valueOf(realProduction));
                            break;
                    }

                    BaseCommand reportCommand = null;
                    float dValue = snv.setfloat(realProduction - (planproduction / 12.0f), 2);
                    String checkVlaue = "";
                    if (Math.abs(dValue) > 100) {
                        StaticLog.info("OPC读取数据错误，产进计算结果为：" + realProduction);
                        continue;
                    }
                    if (dValue > 0) {
                        reportCommand = new ReportCommand();
                        ((ReportCommand) reportCommand).setReportMsg("[" + ts.getStationname() + "]超产：" + dValue);
                        ((ReportCommand) reportCommand).setWarnLevel("报警级别为" + NbotStringUtil.getAlarmLevelStr("2"));
                        ((ReportCommand) reportCommand).setValueNow("现场实时产量为：" + realProduction);
                        checkVlaue = "超产";
                    } else if (dValue < 0) {
                        reportCommand = new ReportCommand();
                        ((ReportCommand) reportCommand).setReportMsg("[" + ts.getStationname() + "]欠产：" + dValue);
                        ((ReportCommand) reportCommand).setWarnLevel("报警级别为" + NbotStringUtil.getAlarmLevelStr("2"));
                        ((ReportCommand) reportCommand).setValueNow("现场实时产量为：" + realProduction);
                        checkVlaue = "欠产";
                    }
                    if (reportCommand != null) {
                        //查询报警记录里当前opc点，在10min内是否有相同值的报警，有则不发送报警，无则发送报警
                        Calendar beforeTime = Calendar.getInstance();
                        beforeTime.add(Calendar.MINUTE, -Integer.parseInt("60"));//计算n分钟前的date对象
                        Date beforeD = beforeTime.getTime();
                        List<ChecklogDO> logs = null;
                        String disp = ((ReportCommand) reportCommand).getReportMsg();
                        logs = checklogService.logInNminsBydisp(disp, checkVlaue, beforeD.getTime() / 1000);

                        //将当前报警值进行保存
                        //如果n分钟内没有相同，则发送报警指令
                        if (logs.isEmpty()) {
                            ChecklogDO checklog = new ChecklogDO();
                            int priority = 1;
                            ((ReportCommand) reportCommand).setPriority(priority);
                            try {
                                BotServer.addUartMsg(reportCommand);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }

                            log.debug("BotServer.comandQueue.size()：" + BotServer.uartQueue.size());
                            log.debug("发送生产报警指令：" + reportCommand.toString());

                            checklog.setTag(ts.getStationname());
                            checklog.setDispdesc(disp);
                            checklog.setChecktimestamp(new Date());
                            checklog.setCheckvalue(checkVlaue);
                            checklog.setTruthvalue(String.valueOf(realProduction));
                            checklog.setAlarmlevel("即时产量");
                            checklogService.insert(checklog);
                        }
                    }

                    updata = new TransmissstationopckeyDO();
                    float classGroupProduction = snv.setfloat(Float.parseFloat(transmissstationopckeyService.get(updateKey).getBeforeproduction()) + realProduction,2);
                    if (hours % 8 == 7) {//交班
                        reportCommand = null;
                        checkVlaue = "";
                        dValue = snv.setfloat(classGroupProduction - (planproduction / 3.0f), 2);
                        if (hours == 15) {
                            updata.setClassone(String.valueOf(classGroupProduction));
                            checkVlaue = "一班";
                            ethp.setClassone(String.valueOf(dValue));
                        } else if (hours == 23) {
                            updata.setClasstwo(String.valueOf(classGroupProduction));
                            checkVlaue = "二班";
                            ethp.setClasstwo(String.valueOf(dValue));
                        } else if (hours == 7) {
                            updata.setClassthree(String.valueOf(classGroupProduction));
                            checkVlaue = "三班";
                            ethp.setClassthree(String.valueOf(dValue));
                        }
                        if (dValue > 0) {
                            reportCommand = new ReportCommand();
                            ((ReportCommand) reportCommand).setReportMsg("[" + ts.getStationname() + "]" + checkVlaue + "超产：" + dValue);
                            ((ReportCommand) reportCommand).setWarnLevel("报警级别为" + NbotStringUtil.getAlarmLevelStr("2"));
                            ((ReportCommand) reportCommand).setValueNow("班组实际产量为：" + classGroupProduction);
                            checkVlaue = "超产";
                        } else if (dValue < 0) {
                            reportCommand = new ReportCommand();
                            ((ReportCommand) reportCommand).setReportMsg("[" + ts.getStationname() + "]" + checkVlaue + "欠产：" + dValue);
                            ((ReportCommand) reportCommand).setWarnLevel("报警级别为" + NbotStringUtil.getAlarmLevelStr("2"));
                            ((ReportCommand) reportCommand).setValueNow("班组实际产量为：" + classGroupProduction);
                            checkVlaue = "欠产";
                        }

                        if (reportCommand != null) {
                            //查询报警记录里当前opc点，在10min内是否有相同值的报警，有则不发送报警，无则发送报警
                            Calendar beforeTime = Calendar.getInstance();
                            beforeTime.add(Calendar.MINUTE, -Integer.parseInt("60"));//计算n分钟前的date对象
                            Date beforeD = beforeTime.getTime();
                            List<ChecklogDO> logs = null;
                            String disp = ((ReportCommand) reportCommand).getReportMsg();
                            logs = checklogService.logInNminsBydisp(disp, checkVlaue, beforeD.getTime() / 1000);

                            //将当前报警值进行保存
                            //如果n分钟内没有相同，则发送报警指令
                            if (logs.isEmpty()) {
                                ChecklogDO checklog = new ChecklogDO();
                                int priority = 2;
                                ((ReportCommand) reportCommand).setPriority(priority);
                                try {
                                    BotServer.addUartMsg(reportCommand);
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }

                                log.debug("BotServer.comandQueue.size()：" + BotServer.uartQueue.size());
                                log.debug("发送生产报警指令：" + reportCommand.toString());

                                checklog.setTag(ts.getStationname());
                                checklog.setDispdesc(disp);
                                checklog.setChecktimestamp(new Date());
                                checklog.setCheckvalue(checkVlaue);
                                checklog.setTruthvalue(String.valueOf(classGroupProduction));
                                checklog.setAlarmlevel("班组产量");
                                checklogService.insert(checklog);
                            }
                        }
                        classGroupProduction = 0f;
                    }
                    everytwohoursproductionService.update(ethp);
                    updata.setAutoid(updateKey);
                    updata.setBeforeproduction(String.valueOf(classGroupProduction));
                    transmissstationopckeyService.update(updata);
                }
                server.disconnect();
            }
        }
    }
}
